<template>
  <div class="navigation" ref="nav">
    <ul class="nav"
        @touchstart="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="handleTouchEnd"
    >
      <li
        v-for="letter in letters"
        :key="letter"
        @click="handleLetterClick"
        :ref="letter"
      >{{letter}}</li>
    </ul>
  </div>
</template>
<script>
export default {
  name: 'CityNavigation',
  props: {
    cities: Object,
    listOffsetTop: Number
  },
  data() {
    return {
      startY: 0
    }
  },
  computed:{
    letters(){
      let letters = []
      for (let i in this.cities) {
        letters.push(i)
      }
      return letters
    }
  },
  updated() {
    // 导航条到swiper的距离
    let navOffsetTop = this.$refs['nav'].offsetTop;
    // 距离顶部高度 = list组件到顶部距离 + 导航条到list顶部距离
    this.startY = this.listOffsetTop + navOffsetTop;
    // 元素高度
    this.letterHeight = this.$refs['A'][0].clientHeight;
  },
  methods:{
    handleLetterClick(e) {
      this.$emit('clickLetter', e.target.innerText)
    },
    handleTouchStart(){
      this.touchStatus = true;
    },
    handleTouchMove(e){
      //console.log(e)
      if(this.touchStatus){
        //使用settimeout进行节流控制
        if(this.timer){
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(()=>{
          const index = Math.floor((e.touches[0].clientY - this.startY) / this.letterHeight)
          if(index >= 1 && index <= this.letters.length){
            this.$emit('changeLetter', this.letters[index-1])
          }
        }, 16)
      }
    },
    handleTouchEnd(){
      // 向父组件传递信息，标识滑动结束
      this.$emit('touchEnd')
    },
  }
}
</script>
<style lang="scss" scoped>
@import '../../../assets/base.scss';
  .navigation{
    position: absolute;
    top: 100px;
    right: 20px;
    z-index: 2;
  }
  .nav{
    display: flex;
    flex-direction: column;
    li{
      width: 40px;
      text-align: center;
      line-height: 40px;
      color: $headerColor;
    }
  }
</style>
